package com.example.nna.voz;

import java.net.URL;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nna.main.R;
import com.example.nna.util.UserInfo;
import com.example.nna.util.loadAssets;
public class Voz extends mainclass{
	static final String URL="http://vozforums.com/";
	public static final int MSG_SUBSCRIBE = 25;
	public static final int MSG_GOTO = 24;
	public static final int MSG_ALERTCOMMENT = 22;
	public static final int MSG_LIKEPAGE = 21;
	public static final int MSG_EDITGET= 20;
	public static final int MSG_CLICKEDIT= 19;
	public static final int MSG_CLICKMUTILQUOTE= 18;
	public static final int MSG_CLICKQUOTE = 17;
	public static final int MSG_CLICKREPLY = 16;
	
	public static final int MSG_QUICKREPLY = 13;
	public static final int MSG_QUOTEREPLY = 14;
	public static final int MSG_QUOTEGET = 15;
	public static final int MSG_LOGIN = 11;
	public static final int MSG_LOGOUT = 12;
	public static final int MSG_PAGE1 = 0;
	public static final int MSG_PAGE2 = 1;
	public static final int MSG_PAGE3 = 2;
	public static final int MSG_PAGETEST = 3;
	public static final int PASER_PASER = 0;
	public static final int PASER_LOGIN = 1;
	public static final int PASER_LOGOUT = 2;
	public static final int PASER_QUICKREPLY = 3;
	public static final int PASER_QUOTEREPLY = 4;
	public static final int PASER_QUOTEGET = 5;
	public static final int PASER_EDITREPLY = 6;
	public static final int PASER_SUBSCRIBE = 7;
	public static final int PASER_USERCP = 8;
	public static final double FONTSCALE_MIN = 0.5;
	public static final double FONTSCALE_MAX = 2.5;
	
	
	public URL feedUrl;
	
	private ConnectivityManager connections;
	private listViewCustom1 adapter;
	private ListView mMainList;
	private Parser1 mParser;
	public static int width;
	public static int height;
	private ProgressDialog progressDialog;
    public static loadAssets mAssests;

    private TextView m_TextLogin;
    private PaserTask mTask;
    private int stateConenct;
    
    private AlertDialog.Builder alert;
    private View textEntryView;
    private LayoutInflater factory;
    private EditText edit1 ;
    private EditText edit2 ;
    private TextView text1 ;
    private TextView text2 ;
    
    public static float mTextSize;
    private ParserUserCP mPaserUserCP;
    private listViewCustomSubscribe adapterUserCP;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parser_html);
        mMainList = (ListView)findViewById(R.id.mainlist);
        mContext = this;
        mActivity = this;
        mUser = new UserInfo();
        getRevolution();
        mNotifEnable = true;
        mNotifTimer = 10;
        mNotifTimerSelection = 2;
        mTextSize =  1.4F;
        mAssests = new loadAssets(mContext);
        initService();
        if(checkNetwork()){
	        progressDialog = new ProgressDialog(this);
	        progressDialog.setCancelable(false);
	        progressDialog.setMessage("Loading data......");
	        mParser = new Parser1(URL);
		    adapter = new listViewCustom1(mActivity,mHandler,mParser.getContain());
		    adapter.setSize(mTextSize);
		    mMainList.setAdapter(adapter);
	      	if(checkNetwork()){
	      		mHandler.obtainMessage(0).sendToTarget();
	      		//http://vozforums.com/showthread.php?t=851372
	      		//String temp ="http://vozforums.com/showthread.php?t=851372";mHandler.obtainMessage(MSG_PAGE3,temp).sendToTarget();
	      	}
        }else{
        	alertDialog();
        	alertDialogDisconnect();
        	alert.setPositiveButton("Please check network", new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int whichButton) {
		    		
		    	}
		    });
			alert.show();
        }
        
        m_TextLogin = (TextView)findViewById(R.id.mainLogin);
        m_TextLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog();
			    if(mParser.mUserInfo().isLogin() != true){
				    alert.setTitle("Log in" );
				    text1.setVisibility(View.VISIBLE);
				    text2.setVisibility(View.VISIBLE);
				    edit1.setVisibility(View.VISIBLE);
				    edit2.setVisibility(View.VISIBLE);
				    text1.setText("Username:");
				    text2.setText("Password:");

			    }else{
			    	alert.setTitle("Log out" );
				    text1.setVisibility(View.GONE);
				    text2.setVisibility(View.GONE);
				    edit1.setVisibility(View.GONE);
				    edit2.setVisibility(View.GONE);
			    }
			    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		if(mParser.mUserInfo().isLogin() != true){
				    		mUser.add(edit1.getText().toString(), edit2.getText().toString());
			    			mHandler.obtainMessage(MSG_LOGIN,URL).sendToTarget();
			    		}else{
			    			mHandler.obtainMessage(MSG_LOGOUT,URL).sendToTarget();
			    		}
			    	}
			    });
			    alert.show();
			}
		});
    }
    protected void initService(){
    	//iService = new Intent(mContext, MyService.class);
    	//bindService(iService, connection, Context.BIND_AUTO_CREATE);	
    	startService(new Intent(mContext, MyService.class));
    }
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	Log.d("nna","Destroy");
    	
    }
    @Override
    protected void onStop() {
    	// TODO Auto-generated method stub
    	super.onStop();
    	Log.d("nna","stop");
    }
    @Override
    protected void onRestart() {
    	// TODO Auto-generated method stub
    	super.onRestart();
    	Log.d("nna","Restart");
    	if(mParser.mUserInfo().isLogin()==true){
			m_TextLogin.setText(mParser.mUserInfo().User());
			Log.d("nna","112"+mParser.mUserInfo().User() );
		}else m_TextLogin.setText("Log on");
    }
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();

    };
    public float getSize(){
    	return mTextSize;
    }

    public class PaserTask extends AsyncTask<Integer, Void, Integer>{

		@Override
		protected Integer doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			switch (params[0]) {
			case PASER_PASER:
				stateConenct = mParser.parser();
				if(stateConenct==-1){
					Log.d("nna", "Cannot connect Vozforums");
				}
				break;
			case PASER_LOGIN:
				stateConenct = mParser.Login(mUser);
				if(stateConenct==-1){
					Log.d("nna", "Cannot connect Vozforums");
				}
				break;	
			case PASER_LOGOUT:
				stateConenct = mParser.Logout();
				if(stateConenct==-1){
					Log.d("nna", "Cannot connect Vozforums");
				}
				break;
			case PASER_USERCP:
				stateConenct = mPaserUserCP.parser();
				break;
			default:
				break;
			}
			return params[0];
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			progressDialog.show();
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			progressDialog.dismiss();
			switch (stateConenct) {
			case 0:
				if(result != PASER_USERCP){
					if(mParser.mUserInfo().isLogin()==true){
						m_TextLogin.setText(mParser.mUserInfo().User());
					}else m_TextLogin.setText("Log on");
					adapter.notifyDataSetChanged();
				}else{
					adapterUserCP.notifyDataSetChanged();
				}
				break;
			case -1:
				alertDialog();
				alertDialogDisconnect();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		mHandler.obtainMessage(0).sendToTarget();
			    	}
			    });
				alert.show();
				break;
			case -2:
				alertDialog();
				alertDialogLogin();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		m_TextLogin.performClick();
			    	}
			    });
				alert.show();
				break;
			default:
				break;
			}
			
		}
     }
    boolean checkNetwork(){
    	connections = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connections.getActiveNetworkInfo();
        if((info != null) && (info.getState() != null) ){
        	Toast.makeText(mContext, "connected intetnet", Toast.LENGTH_SHORT).show();
        	return true;
        }else{
        	Toast.makeText(mContext, "cannot access intetnet", Toast.LENGTH_SHORT).show();
        	return false;
        }
    }
    @SuppressWarnings("deprecation")
	void getRevolution(){
    	Point size = new Point();
    	WindowManager w = getWindowManager();
	    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
	          w.getDefaultDisplay().getSize(size);

	          width = size.x;
	          height = size.y; 
	        }else{
	          Display d = w.getDefaultDisplay(); 
	          width = d.getWidth(); 
	          height = d.getHeight(); 
	       }
    }
    private void alertDialog(){
	    factory = LayoutInflater.from(mContext);
	    textEntryView = factory.inflate(R.layout.login, null);    
	    edit1 = (EditText)textEntryView.findViewById(R.id.alert_edit1);
	    edit2 = (EditText)textEntryView.findViewById(R.id.alert_edit2);
	    text1 = (TextView)textEntryView.findViewById(R.id.alert_txt1);
	    text2 = (TextView)textEntryView.findViewById(R.id.alert_txt2);
	    alert = new AlertDialog.Builder(mContext);
	    alert.setView(textEntryView);
    }
    private void alertDialogDisconnect(){
    	edit1.setVisibility(View.GONE);
    	edit2.setVisibility(View.GONE);
    	text2.setVisibility(View.GONE);
    	text1.setText("Error Connection");
    }
    private void alertDialogLogin(){
    	edit1.setVisibility(View.GONE);
    	edit2.setVisibility(View.GONE);
    	text2.setVisibility(View.GONE);
    	text1.setText("Invalid username or password");
    }
    public final Handler mHandler = new Handler(){
    	@Override
    	public void handleMessage(Message msg) {
    		 int pos ;
    		 switch (msg.what) {
    		 case MSG_PAGE1:
  		        mTask = new PaserTask();
  		        mTask.execute(PASER_PASER);
    			break;

    		 case MSG_PAGE2:
    			 Bundle extras = new Bundle();
    			 if(msg.obj.toString().contains("vozforums.com") == true){
	    			extras.putString("url",msg.obj.toString());
	     			extras.putString("forum","");
	    		} else{
	     			pos = Integer.parseInt(msg.obj.toString());
	     			extras.putString("url",URL+mParser.getContain(pos).UrlForum());
	     			extras.putString("forum",mParser.getContain(pos).Forum());
    			}
    			Intent i = new Intent(mContext,page2.class );
    			i.putExtras(extras);
 				startActivity(i);
		    	break;
    		 case MSG_PAGE3:
    			 extras = new Bundle();
    			 if(msg.obj.toString().contains("vozforums.com") == true){
	    			extras.putString("url",msg.obj.toString());
	     			extras.putString("forum","");
	    		} else{
	     			pos = Integer.parseInt(msg.obj.toString());
	     			extras.putString("url",URL+mParser.getContain(pos).UrlLast());
	     			extras.putString("forum",mParser.getContain(pos).Forum());
    			}
    			i = new Intent(mContext,page3.class );
 				i.putExtras(extras);
 				startActivity(i);
 		    	break;
    		 case MSG_LIKEPAGE:
    			 extras = new Bundle();
    			 extras.putString("url",URL+(String)msg.obj);
			 	 extras.putString("forum","test");
    			 i = new Intent(mContext,page3.class );
 				 i.putExtras(extras);
 				 startActivity(i);
    			 break;
    		 case MSG_PAGETEST:
      			i = new Intent(mContext,page3.class );
      			extras = new Bundle();
      			extras.putString("url",msg.obj.toString());
      			extras.putString("forum","test");
  				i.putExtras(extras);
  				startActivity(i);
  		    	break;	
    		 case MSG_LOGIN:
   		        mTask = new PaserTask();
		        mTask.execute(PASER_LOGIN);
     			break;
    		 case MSG_LOGOUT:
    			mTask = new PaserTask();
 		        mTask.execute(PASER_LOGOUT);
    			break;
		     }
    	};
    };
}

